angular.module('UCX.Cmis')
.directive('inputEmailCdrm',(CmisService, localStorageService, ModelService,$window,$timeout, $uibModal, Utils, $translate,ApiService)->

  scope:{
    email: '=',
    newEmail: '='
    curChooseUser: '='
    users: '='
    chooseUser: '='
    lang: '='
    placeholder: '='
    choseUsersArr: '='
    fileCdocId: '='
  }

#  http://codepen.io/prophet_w/pen/GWjejg
  restrict:'E'
#  replace:true
  templateUrl: 'template-path/input-emails-for-cdrm.html',
  link:(scope, element, attr)->
    console.log('====scope.email====');
    console.log(scope.email);
    generateUser=(email,emailDomain)->
      # emailDomain 特殊处理
      if emailDomain
        return {
          name:$translate.instant('enterprise_all_users')
          isValidInput:true
          avatar:''
          selected:false
          emailDomain:Utils.getEmailDomainFrom(CmisService.email)
          groupID:''
          groupName:''
          isGroup: 0
          permissions:[0,0,0]
          online:0
          onlineDays: ''
          onlineDate:''
          permData:{
            copyCode:0
            editCode:0
            printCode:0
          }
        }
      # email not only email maybe group name
      for user in scope.users
        if user.name==email
          return
      # online:0  never
      # online:1  days
      # online:2  specific date
      return {
        name:email
        isValidInput:Utils.isValidEmail(email) || Utils.isInGroup(email)
        avatar:email
        emailDomain:''
        selected:false
        groupID:''
        groupName:''
        isGroup: 0
        permissions:[0,0,0]
        online:0
        onlineDays: ''
        onlineDate:''
        permData:{
          copyCode:0
          editCode:0
          printCode:0
        }
      }
    if(scope.lang && scope.lang.indexOf('-')!=-1)
      $translate.use(scope.lang.split('-')[1])
    scope.placeholderTxt=$translate.instant(scope.placeholder)
    scope.$on('protect',()->
      scope.addNewUser()
    )
    scope.addEnterpriseAllUsers=()->
      console.log('------11')
      console.log(scope.users)
      scope.users=[]
      scope.choseUsersArr=[]
      scope.curChooseUser=null
      enterpriseUser=generateUser(null,true)
      scope.users.push(enterpriseUser)
      scope.chooseUser(enterpriseUser)
    scope.chooseUserByCheckbox=(user,e)->
  # if cur user is selected cancel select
      if e
        e.stopPropagation()
      if user.selected
        user.selected=false
        console.log('sdadsadsa')
        if scope.choseUsersArr && scope.choseUsersArr.length
          userIndex=scope.choseUsersArr.indexOf(user)
        if userIndex>-1
          scope.choseUsersArr.splice(userIndex,1)
        scope.curChooseUser=scope.choseUsersArr.length && scope.choseUsersArr || null
      else
        scope.curChooseUser=user
        user.selected=true
        scope.choseUsersArr.push(user)
    scope.selectAllUsers=()->
      for user in scope.users
        user.selected=true
        scope.choseUsersArr.push(user)
    scope.addNewUser=(event)->
      if scope.newEmail
        emailList = scope.newEmail.replace(/\s+/g,';');
        emailList = emailList.replace(/\；+/g,';');
        emailList = emailList.replace(/\;+/g,';');
        emailList = emailList.replace(/\,+/g,';');
        emailList = emailList.replace(/\，+/g,';');

        if(emailList.indexOf(';')!=-1)
          emailArr = emailList.split(';')
          for email in emailArr
            if email
              user = generateUser(email)
              if user
                scope.users.push(user)
                scope.chooseUser(user)
        else
          user = generateUser(scope.newEmail)
          if user
            scope.users.push(user)
            scope.chooseUser(user)
        scope.newEmail=''
        if event
          event.preventDefault()
    deleteUser=(index,user)->
      scope.users.splice(index,1)
      hasSelectedFile=false
      for user0 in scope.users
        if user0.selected==true
          hasSelectedFile=true
      if !hasSelectedFile
        scope.curChooseUser=null
      if scope.choseUsersArr.length>0
        for index1,user1 of scope.choseUsersArr
          if user1.name == user.name
            scope.choseUsersArr.splice(index1,1)
    scope.deleteUser=(index,user)->
      if user.drmMsgId
        # 数据是服务器返回的
        # confirm to delete
        $translate('cDrm_perm_delete_confirm').then (text)->
          Utils.confirm text,'','','', ()->
            Utils.showLoading()
            ApiService.deleteUserPermInCDrm(user.drmMsgId,scope.fileCdocId,()->
              Utils.success('删除成功')
              Utils.closeLoading()
              deleteUser(index,user)
            ,()->
              Utils.closeLoading()
              Utils.warning('删除失败，请稍后在试')
            )


      else
        #
        deleteUser(index,user)


    scope.handleKeyPress=(event)->
  # handle ctrl + v paste
  #    if event.metaKey==true && event.keyCode==86 || event.ctrlKey==true && event.keyCode==86
      if navigator.userAgent.toLowerCase().indexOf('android')>-1
        if event && event.which==13
          if !scope.newEmail
            if event
              event.preventDefault()
          else
            scope.addNewUser()
            $timeout(()->
              $('#user-input-area').val('')
            )
          return false
        return
#      if event && (event.keyCode==8 || event.key=='Backspace')
#        if scope.users.length && !scope.newEmail
#          scope.users.splice(scope.users.length-1,1)
      # handle 'enter' key 'space' key ';'  ','
      # 中文输入法输入时没有触发 keypress 事件 可以实现中文enter 变成英文 不触发 addNewUser 事件
      # delete 的时候没有触发key press 事件
      if event && event.which==13
        if !scope.newEmail
          if event
            event.preventDefault()
        else
          scope.addNewUser()
          $timeout(()->
            $('#user-input-area').val('')
          )
        return false
    scope.handleKeyUp=(event)->
      # 安卓 chrome keyup 无法识别 key  直接全部判定为  keyCode==229

      if navigator.userAgent.toLowerCase().indexOf('android')>-1
        if event && event!="Unidentified" && event.keyCode==13
          if !scope.newEmail
            if event
              event.preventDefault()
            return false
          else
            scope.addNewUser()
        return
#      console.log(event);
#      if event && (event.keyCode==8 || event.key=='Backspace')
#        if scope.users.length && !scope.newEmail
#          scope.users.splice(scope.users.length-1,1)
      # handle 'enter' key 'space' key ';'  ','
      if event && event!="Unidentified" && (event.keyCode==188 || event.keyCode==32 || event.keyCode==186 || event.keyCode==229)
        if !scope.newEmail
          if event
            event.preventDefault()
          return false
        else
          scope.addNewUser()
    scope.$on('add-user',()->
      scope.addNewUser()
    )
    scope.clearNewUserList=()->
      scope.users=[]
      scope.newEmail=''
      scope.feedback=false
      scope.postMessage=''

)
